package com.ruoyi.web.controller.system;

import java.security.PrivateKey;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.framework.config.properties.RsaKeyProperties;
import com.ruoyi.framework.util.RsaUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserAddDto;
import com.ruoyi.system.domain.SysUserSelectDto;
import com.ruoyi.system.domain.SysUserUpdateDto;
import com.ruoyi.system.domain.SysUserUpdatePwdDto;
import com.ruoyi.system.dto.register.RegisterDto;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.service.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "（系统用户管理")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @ApiOperation(value = "用户列表")
    public TableDataInfo list(SysUserSelectDto userSelectDto) {
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userSelectDto, sysUser);
        List<SysUser> list = userService.selectUserList(sysUser);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        List<SysUser> sysUsers= list.stream().
                sorted(Comparator.comparing(SysUser::getCreateTime).reversed()).
                skip((long) (pageNum - 1) * pageSize).limit(pageSize).
                collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(sysUsers);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @PostMapping("/geyById")
    @ResponseBody
    @ApiOperation(value = "根据id获取用户信息", response = SysUser.class)
    public SysUser geyById(Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        return sysUser;
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        // AjaxResult ajax = AjaxResult.success();
        Map<String, Object> map = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            map.put("data", sysUser);
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return AjaxResult.success(map);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:adds')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation(value = "新增保存用户")
    public AjaxResult addSave(@Validated @RequestBody SysUserAddDto addDto) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(addDto, user);
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String token = tokenService.createToken(loginUser);
        return toAjax(userService.insertUser(user, token));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping
    @ApiOperation(value = "修改保存用户")
    public AjaxResult edit(@Validated @RequestBody SysUserUpdateDto updateDto) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(updateDto, user);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String token = tokenService.createToken(loginUser);
        return toAjax(userService.updateUser(user, token));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @ApiOperation(value = "删除用户")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String token = tokenService.createToken(loginUser);
        return toAjax(userService.deleteUserByIds(userIds, token));
    }

    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    public AjaxResult resetPwd(@RequestBody SysUserUpdatePwdDto updatePwdDto) throws Exception {
        if(updatePwdDto.getUserId() == null){
            return AjaxResult.error("用户ID不能为空");
        }
        if(StringUtils.isBlank(updatePwdDto.getNewPassword())){
            return AjaxResult.error("新密码不能为空");
        }
        if(StringUtils.isBlank(updatePwdDto.getOldPassword())){
            return AjaxResult.error("原密码不能为空");
        }
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(updatePwdDto, sysUser);
        userService.checkUserAllowed(sysUser);
//        userService.checkUserDataScope(sysUser.getUserId());
        String oldPassword = updatePwdDto.getOldPassword();
        String newPassword = updatePwdDto.getNewPassword();
        PrivateKey privateKey = rsaKeyProperties.getPrivateKey();
        String decryptOldPassword = RsaUtils.decrypt(oldPassword, privateKey);
        String decryptNewPassword = RsaUtils.decrypt(newPassword, privateKey);
        SysUser userInFo = userService.selectUserById(updatePwdDto.getUserId());
        if(userInFo == null){
            return AjaxResult.error("用户不存在");
        }
        if(!SecurityUtils.matchesPassword(decryptOldPassword, userInFo.getPassword())){
            return AjaxResult.error("原密码不正确");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(decryptNewPassword));
        sysUser.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(sysUser));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation(value = "状态修改")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String token = tokenService.createToken(loginUser);
        return toAjax(userService.updateUserStatus(user, token));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户编号获取授权角色")
    public AjaxResult<Map<String, Object>> authRole(@PathVariable("userId") Long userId) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        map.put("user", user);
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return AjaxResult.success(map);
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    @ApiOperation(value = "获取部门树列表")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @PostMapping("/ykz/register")
    @ApiOperation("愉快政用户注册")
    public AjaxResult<String> register(@RequestBody RegisterDto registerDto){
        return success(userService.registerYKZUser(registerDto));
    }
}
